package com.zy.explore.db.infrastructure.plugins.multidbsupport.plugin;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.toolkit.JdbcUtils;
import com.zy.explore.db.infrastructure.util.PropertiesUtil;
import org.apache.ibatis.plugin.Interceptor;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 建类说明：sql改变拦截器工厂bean
 *
 * @author 中国印
 * @date 2022年02月16日 23:08:34
 */
@Component
public class SqlChangeInterceptorFactoryBean implements FactoryBean<Interceptor> {

    private static final Map<String, Interceptor> INTERCEPTOR_MAP;

    static {
        INTERCEPTOR_MAP = new HashMap<>();
        // 神通数据库
        INTERCEPTOR_MAP.put(DbType.OSCAR.getDb(), new OscarSqlChangeInterceptor());
        // 达梦数据库
        INTERCEPTOR_MAP.put(DbType.DM.getDb(), new DmSqlChangeInterceptor());
        // oracle数据库
        INTERCEPTOR_MAP.put(DbType.ORACLE.getDb(), new OracleSqlChangeInterceptor());
        // 人大金仓数据库
        INTERCEPTOR_MAP.put(DbType.KINGBASE_ES.getDb(), new KingbaseSqlChangeInterceptor());
    }

    @Override
    public Interceptor getObject() {
        String dbUrl = PropertiesUtil.getProperty("spring.datasource.url", "");
        String dbType = JdbcUtils.getDbType(dbUrl).getDb();
        Interceptor interceptor = INTERCEPTOR_MAP.get(dbType);
        if (interceptor == null) {
            // 默认mysql数据库
            return new DefaultSqlChangeInterceptor();
        }
        return interceptor;
    }

    @Override
    public Class<?> getObjectType() {
        return null;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }

}
